package com.weiyuwqj.server.service.asset.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.common.RepayPlan;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.BasAssetsPackage;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BusAssetPackagePlan;
import com.weiyuwqj.api.model.BusAssetRepay;
import com.weiyuwqj.api.model.*;
import com.weiyuwqj.api.model.vo.BatchInvestVo;
//import com.weiyuwqj.api.hengfeng.param.vo.HfBidGrantVo;
import com.weiyuwqj.api.service.BasAssetsPackageService;
import com.weiyuwqj.api.service.BasItemService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.*;
//import com.weiyuwqj.server.pay.InvestApi;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.user.invest.*;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.server.service.invest.module.AssetPackageRepayModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by zhangyong on 2017/3/28.
 * 资产打包
 */
@Service("assetsPackageService")
public class BasAssetsPackageServiceImpl extends BaseServiceImpl<BasAssetsPackage> implements BasAssetsPackageService {

    @Autowired
    BasAssetsPackageMapper assetsPackageMapper;
    @Autowired
    BasItemMapper itemMapper;
    @Autowired
    BasCouponMapper couponMapper;
    @Autowired
    DealModule dealModule;
    @Autowired
    BusBonusRebateMapper bonusRebateMapper;
    @Autowired
    BusAccountMapper accountMapper;
    @Autowired
    BusAssetInvestMapper assetInvestMapper;
    @Autowired
    BusAssetCollectMapper assetCollectMapper;
    @Autowired
    BusIncomeStatMapper incomeStatMapper;
    @Autowired
    BusVerifyLogMapper verifyLogMapper;
    @Autowired
    BusAssetRepayMapper assetRepayMapper;
    @Autowired
    BusAssetPackagePlanMapper assetPackagePlanMapper;
    @Autowired
    AssetPackageRepayModule packageRepayModule;
    @Autowired
    BasItemService itemService;
    @Autowired
    BasUserMapper userMapper;
//    @Autowired
//    PlatformApi platformApi;
//    @Autowired
//    InvestApi investApi;


    /**
     * 查询包列表
     *
     * @param assetsPackage
     * @return
     */
    @Override
    public PageList getPackageList(Paginator p, BasAssetsPackage assetsPackage) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BasAssetsPackage> list = assetsPackageMapper.getPackageList(assetsPackage);
        return new PageList(list);
    }

    /**
     * 资产打包
     *
     * @param itemStr     项目id字符串
     * @param sysUserId   操作人员id
     * @param addip       添加ip
     * @param packageName 包名称
     */
    @Override
    public void insertPackage(String itemStr, Integer sysUserId, String packageName, String addip) {
        if (StringUtils.isNull(itemStr)) {
            throw new CrowdException("asset.package.item_id_not_exists");
        }
        //截取标id的字符串
        String[] itemIds = itemStr.split(",");

        //循环判断标的利率，期限，还款方式是否相同
        Boolean result = packageCheck(itemIds);
        //判断校验结果
        if (result) {
            //插入包表
            BasAssetsPackage assetsPackage = new BasAssetsPackage();
            assetsPackage.setAddip(addip);
            assetsPackage.setAddtime(new Date());
            assetsPackage.setPackageName(packageName);
            assetsPackage.setStatus(1);
            assetsPackage.setSysUserId(sysUserId);
            assetsPackage.setUpdatetime(new Date());
            assetsPackageMapper.insertAssetsPackage(assetsPackage);
            //修改标的包id
            itemMapper.modifyPackageIdById(assetsPackage.getId(), itemIds);
        } else {
            throw new CrowdException("asset.package.item_not_type");
        }

    }

//    /**
//     * 包计划借款人还款到标账户
//     */
//    @Override
//    public Map brrowerPackageRepay(BusAssetRepay assetRepay) {
//        return packageRepayModule.brrowerPackageRepay(assetRepay);
//    }

    /**
     * 根据包id修改包状态
     *
     * @param newStatus
     * @param oldStatus
     * @param id
     * @return
     */
    @Override
    public Integer modifyPackageStatusById(Integer newStatus, Integer oldStatus, Integer id) {
        return assetsPackageMapper.modifyPackageStatusById(newStatus, oldStatus, id);
    }

//    /**
//     * 包还款
//     *
//     * @param packagePlanId 包计划id
//     */
//    @Override
//    public Map packageRepay(Integer packagePlanId, BusAssetRepay assetRepay, BusAssetPackagePlan packagePlan) {
//        return packageRepayModule.packageRepay(packagePlanId, assetRepay, packagePlan);
//    }

//    public Object assetThaw(List<BusAssetInvest> assetInvestList, Integer itemId) {
//        Boolean thaw = true;
//        for (BusAssetInvest itemInvest : assetInvestList) {
//            BasCoupon coupon = couponMapper.getCouponByInvestId(itemInvest.getId());
//            HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//            if (coupon != null) {
//                freezeOrTraw.setAmount(itemInvest.getInvestDealAmount().subtract(coupon.getAmount()).toString());
//            } else {
//                freezeOrTraw.setAmount(itemInvest.getInvestDealAmount().toString());
//            }
//            freezeOrTraw.setFreeze_flg("02");
//            freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(itemInvest.getUserId()).getPlatformId());
//            freezeOrTraw.setRemark(itemInvest.getUserId() + "投资撤回");
//            freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//            freezeOrTraw.setFreeze_order_no(itemInvest.getFreezeOrderNo());
//            try {
//                HfResultBean<HfDataBean> resultBean = platformApi.doFundFreeze(freezeOrTraw);
//            } catch (Exception e) {
//                thaw = false;
//            }
//        }
//        //判断是否完成解冻
//        if (!thaw) {
//            throw new CrowdException("item.recall.thaw_error");
//        }
//        if (null != itemId) {
//            //修改项目复审状态
//            itemMapper.modifyItemFullStatusByItemId(1, 0, itemId);
//        }
//        return Message.OK;
//    }

//    /**
//     * 批量投资
//     *
//     * @param item
//     * @param assetInvestList
//     */
//    @Override
//    public Map batchInvest(BasItem item, List<BusAssetInvest> assetInvestList) {
//        //批量投资
//        List<BatchInvestVo> batchInvestVos = new ArrayList<>();
//        for (BusAssetInvest itemInvest : assetInvestList) {
//            //查询红包
//            BasCoupon coupon = couponMapper.getCouponByInvestId(itemInvest.getId());
//            //查询用户信息
//            BasUser user = userMapper.selectByPrimaryKey(itemInvest.getUserId());
//            BatchInvestVo batchInvestVo = new BatchInvestVo();
//            if (null == coupon) {
//                batchInvestVo.setCouponAmt("0");
//            } else {
//                batchInvestVo.setCouponAmt(coupon.getAmount().toString());
//            }
//            batchInvestVo.setDetailNo(itemInvest.getInvestOrder());
//            batchInvestVo.setExperienceAmt("0");
//            batchInvestVo.setInInterest("0");
//            batchInvestVo.setSelfAmt(itemInvest.getInvestDealAmount().toString());
//            batchInvestVo.setUser(user);
//            batchInvestVos.add(batchInvestVo);
//        }
//        //请求恒丰
//        HfResultBean result = investApi.createInvest(batchInvestVos, item);
//        if (!result.isSuccess()) {
//            Map resultMap = new HashMap();
//            resultMap.put("result", "fail");
//            resultMap.put("messageText", "批量投资错误");
//            return resultMap;
//        }
//
//        //修改项目状态
//        itemMapper.modifyItemFullStatusByItemId(2, 1, item.getId());
//        return Message.OK;
//    }

//    /**
//     * 成标
//     *
//     * @param itemId
//     * @param repayTime
//     * @param item
//     * @param assetInvestList
//     * @return
//     */
//    public Date assetCreatBid(int itemId, Date repayTime, BasItem item, List<BusAssetInvest> assetInvestList, Integer packageId) {
//        //本金
//        BigDecimal itemPrincial = BigDecimal.ZERO;
//        //利息
//        BigDecimal itemInterest = BigDecimal.ZERO;
//        //统计每个投资的人的分期数据
//        List<BigDecimal[]> princialList = new ArrayList<>(assetInvestList.size());
//        List<BigDecimal[]> interestList = new ArrayList<>(assetInvestList.size());
//        //循环投资人列表
//        for (int i = 0; i < assetInvestList.size(); i++) {
//            BusAssetInvest assetInvest = assetInvestList.get(i);
//            //根据项目利率计算利息
//            List<RepayPlan> repayPlanList = Calculator.getPlanTime(assetInvest.getInvestDealAmount(), item);//项目利率的
//            //投资本金
//            BigDecimal investPrincial = BigDecimal.ZERO;
//            //投资利息
//            BigDecimal investInterest = BigDecimal.ZERO;
//            //本金待收数组
//            BigDecimal[] princialCollectArray = new BigDecimal[repayPlanList.size()];
//            //利息待收数组
//            BigDecimal[] interestCollectArray = new BigDecimal[repayPlanList.size()];
//            for (int j = 0; j < 1; j++) {
//                RepayPlan plan = repayPlanList.get(j);
//                //插入资产待收表
//                BusAssetCollect collect = new BusAssetCollect();
//                collect.setItemId(itemId);
//                collect.setPackageId(packageId);
//                collect.setCollectAmount(plan.getAccount());
//                collect.setCollectTotalPeriod(repayPlanList.size());
//                collect.setCollectCurrentPeriod(plan.getPeriod());
//                collect.setCollectPrincipal(plan.getPrincipal());
//                collect.setCollectInterest(plan.getInterest());
//                collect.setCollectTime(plan.getEndTime());
//                collect.setActualCollectAmount(BigDecimal.ZERO);
//                collect.setActualCollectPrincipal(BigDecimal.ZERO);
//                collect.setActualCollectInterest(BigDecimal.ZERO);
//                collect.setAddip(IpUtils.get());
//                collect.setAddtime(new Date());
//                collect.setInvestId(assetInvest.getId());
//                collect.setInvestUserId(assetInvest.getUserId());
//                collect.setCollectStatus(0);
//                collect.setDebtTransferStatus(0);
//                collect.setAdditionalRateAmount(BigDecimal.ZERO);
//                //查询用户信息
//                BasUser user = userMapper.selectByPrimaryKey(assetInvest.getUserId());
//                collect.setPlatformId(user.getPlatformId());
//                assetCollectMapper.insert(collect);
//
//                princialCollectArray[j] = plan.getPrincipal();
//                interestCollectArray[j] = plan.getInterest();
//                investInterest = investInterest.add(plan.getInterest());
//                investPrincial = investPrincial.add(plan.getPrincipal());
//            }
//            princialList.add(princialCollectArray);
//            interestList.add(interestCollectArray);
//            //投标时已经计算预计回收金额、利息，现在清0重新计算，以复审后为准
//            assetInvest.setCollectAmount(BigDecimal.ZERO);
//            assetInvest.setCollectInterest(BigDecimal.ZERO);
//            assetInvest.setCollectPrincipal(BigDecimal.ZERO);
//            //修改状态，并修改投资金额
//            assetInvestMapper.updateAssetInvestStatus(0, 1, assetInvest.getId());
//            assetInvestMapper.updateAssetFullInvestCollect(investPrincial, investInterest, assetInvest.getId());
//
//            itemPrincial = itemPrincial.add(investPrincial);
//            itemInterest = itemInterest.add(investInterest);
//            //扣除用户冻结金额
//            DealAction deduct = new InvestDeductDealAction();
//            deduct.deal(assetInvest.getUserId(), assetInvest.getInvestDealAmount(), "扣除" + item.getItemName() + "项目投资冻结资金");
//            dealModule.dealAction(deduct);
//            //产生用户待收金额
//            DealAction wait = new GenerateWaitDealAction();
//            wait.deal(assetInvest.getUserId(), assetInvest.getInvestDealAmount().add(investInterest), item.getItemName() + "产生待收资金");
//            dealModule.dealAction(wait);
//
//            //复审通过使income_stat表修改待收
//            BusAssetInvest busItemInvest = assetInvestList.get(i);
//            Map<String, Object> mapStat = new HashMap<>();
//            mapStat.put("waitIncome", investInterest);
//            mapStat.put("userId", busItemInvest.getUserId());
//            mapStat.put("earnedIncome", 0);
//            mapStat.put("totalIncome", investInterest);
//            incomeStatMapper.updateByWaitEarned(mapStat);
//        }
//        //借款人动作
//        if (princialList.size() > 0) {
//            int planLength = princialList.get(0).length;
//            BigDecimal loanSum = BigDecimal.ZERO;//总待还
//            for (int j = 0; j < 1; j++) {
//                BigDecimal princial = BigDecimal.ZERO;
//                BigDecimal interest = BigDecimal.ZERO;
//                BigDecimal additional = BigDecimal.ZERO;
//                for (int i = 0; i < princialList.size(); i++) {
//                    BigDecimal[] pa = princialList.get(i);
//                    BigDecimal[] ia = interestList.get(i);
//                    princial = princial.add(pa[j]);
//                    interest = interest.add(ia[j]);
//                }
//                BusAssetRepay repay = new BusAssetRepay();
//                BigDecimal amount = princial.add(interest);
//                repay.setRepayUserId(item.getItemUserId());
//                repay.setRepayAmount(amount);
//                repay.setRepayPrincipal(princial);
//                repay.setAdditionalRateAmount(additional);
//                repay.setRepayInterest(interest);
//                repay.setItemId(itemId);
//                repay.setRepayCurrentPeriod(j + 1);
//                repay.setRepayTotalPeriod(planLength);
//                repay.setStatus(0);
//                repay.setPackageId(item.getAssetPackageId());
//                repay.setActualRepayAmount(BigDecimal.ZERO);
//                repay.setActualRepayInterest(BigDecimal.ZERO);
//                repay.setActualRepayPrincipal(BigDecimal.ZERO);
//                Date verifyDatetime = DateUtils.setDayLast(new Date());
//                repay.setRepayTime(DateUtils.addTime(1, DateUtils.setDayLast(verifyDatetime), (j + 1) * 30));
//                repay.setPackageId(packageId);
//                assetRepayMapper.insert(repay);
//                repayTime = repay.getRepayTime();
//
//                loanSum = loanSum.add(amount);
//            }
//            //借款人收到资金
//            DealAction receiveAction = new ReceiveLendDealAction();
//            receiveAction.deal(item.getItemUserId(), item.getItemOngoingAccount(), "收到" + item.getItemName() + "项目资金" + item.getItemOngoingAccount() + "元");
//            int receiveCount = dealModule.dealAction(receiveAction);
//            if (receiveCount < 1) {
//                throw new CrowdException("update_error");
//            }
//
//            //借款人增加项目待还
//            DealAction repayAction = new RepayAmountDealAction();
//            repayAction.deal(item.getItemUserId(), loanSum, item.getItemName() + "产生待还金额");
//            int repayCount = dealModule.dealAction(repayAction);
//            if (repayCount < 1) {
//                throw new CrowdException("update_error");
//            }
//
//            BigDecimal sum = BigDecimal.ZERO;
//            for (BusAssetInvest itemInvest : assetInvestList) {
//                sum = sum.add(itemInvest.getInvestDealAmount()); // 实际成交金额
//            }
//            String orderNo = RandomCodesUtils.createRandom(true, 8) + itemId; // 生成放款订单号
//            HfBidGrantVo bidGrantVo = new HfBidGrantVo();
//            bidGrantVo.setBidId(itemId + ""); // 标ID
//            bidGrantVo.setTotalNum(assetInvestList.size());
//            bidGrantVo.setTotalAmount(sum.multiply(new BigDecimal(100)).longValue());
//            bidGrantVo.setUserId(item.getItemUserId().toString());
//            bidGrantVo.setOrderId(orderNo); // 放款订单号
//            bidGrantVo.setGrantAmount(BigDecimal.ONE.longValue()); // 放款总金额=投资订单总金额
////            bidGrantVo.setAmount(sum.multiply(new BigDecimal(100)).subtract(BigDecimal.ONE).longValue());// 分润金额
////            bidGrantVo.setSubOrderId(orderNo + "FR");// 分润单Id
////            bidGrantVo.setReceiveUserId(item.getGuaranteeId().toString());//分润收款用户Id
//            //恒丰接口
//            //List<BusAssetRepay> itemRepays = assetRepayMapper.getAssetRepayListsByItemIdAndCurrentPeriod(itemId); // todo 还款计划表
//            HfResultBean result = investApi.bidGrant(bidGrantVo, new ArrayList<BusItemRepay>());// 成标
//            // {"recode":"20016","remsg":"订单号重复","signdata":"3915624e537518373321d142c15b43ea"}
//            // 返回码，10000为成功; remsg:返回结果描述; data:返回业务数据; 商户请求订单号;    订单状态0:已接受,1:处理中,2:处理成功,3:处理失败;  系统处理日期(yyyyMMddHHmmss));    平台流水号;  签名数据
//            // {"recode":"10000","remsg":"成功","data":{"order_no":"xxx","order_status":"xxx","process_date":"xxx","query_id":"xxx"},"signdata":""}
//            //if (!result.isSuccess()) { // 当且仅当返回码为10000时表示请求成功
//            //    throw new HfException("HfError", result.getMessageText());
//            //}
//        }
//        //项目信息更新
//        itemMapper.updateItemStatus(ItemStatus.FULL_AUDIT, ItemStatus.REPAYING, itemId);
//        BusVerifyLog log = new BusVerifyLog();
//        log.setOperateUserId(1);
//        log.setAddip(IpUtils.get());
//        log.setType((byte) 4);
//        log.setItemId(itemId);
//        log.setAddtime(new Date());
//        log.setStatus((byte) 1);
//        log.setContent("项目复审");
//        verifyLogMapper.insert(log);
//
//        Integer oldStatus = item.getItemStatus();
//        itemMapper.updateItemStatus(oldStatus, ItemStatus.REPAYING, itemId);
//
//        //修改项目状态
//        itemMapper.modifyItemFullStatusByItemId(3, 2, itemId);
//        return repayTime;
//    }

//    /**
//     * 根据标id撤回标
//     *
//     * @param itemId
//     */
//    public void cancelCallBack(Integer itemId) {
//        //查询标信息
//        BasItem item = itemMapper.selectByPrimaryKey(itemId);
//        HfResultBean result = investApi.bidCancel(item);// 标取消
//        // {"recode":"40001","remsg":"无效的产品id","signdata":"4a90154feaee8bd24e253fd8eb87f843"}
//        // 返回码，10000为成功; remsg:返回结果描述; data:返回业务数据; 商户请求订单号;    订单状态0:已接受,1:处理中,2:处理成功,3:处理失败;  系统处理日期(yyyyMMddHHmmss));    平台流水号;  签名数据
//        // {"recode":"10000","remsg":"成功","data":{"order_no":"xxx","order_status":"xxx","process_date":"xxx","query_id":"xxx"},"signdata":""}
//        //if (!result.isSuccess()) { // 当且仅当返回码为10000时表示请求成功
//        //    throw new HfException("HfException", result.getMessageText());
//        //}
//        List<BusAssetInvest> assetInvestList = assetInvestMapper.getAssetInvestListByItemId(itemId);
//        //解冻
//        assetThaw(assetInvestList, itemId);
//
//        for (int i = 0; i < assetInvestList.size(); i++) {
//            BusAssetInvest assetInvest = assetInvestList.get(i);
//            BusAccount busAccount = accountMapper.getBusAccountByUserId(assetInvest.getUserId());
//
//            assetInvestMapper.updateAssetInvestStatus(0, 2, assetInvest.getId());
//
//            //根据investId查找红包
//            BasCoupon coupon = couponMapper.getCouponByInvestId(assetInvest.getId());
//            //修改红包信息
//            if (null != coupon) {
//                Map couponMap = new HashMap();
//                couponMap.put("investId", assetInvest.getId());
//                couponMap.put("useTime", null);
//                couponMap.put("userId", coupon.getUserId());
//                couponMap.put("id", coupon.getId());
//                couponMap.put("newStatus", 2);
//                couponMap.put("oldStatus", 1);
//                couponMapper.updateCouponStatus(couponMap);
//            } else {
//                coupon = new BasCoupon();
//                coupon.setAmount(BigDecimal.ZERO);
//            }
//            DealAction cancelAction = new CancelDealAction();
//            cancelAction.deal(busAccount.getUserId(), assetInvest.getInvestDealAmount().subtract(coupon.getAmount()), item.getItemName() + "项目撤回返回投资资金");
//            dealModule.dealAction(cancelAction);
//        }
//        Integer oldStatus = item.getItemStatus();
//        if (oldStatus == 20) {
//            itemMapper.updateItemStatus(oldStatus, ItemStatus.FULL_FAILURE, itemId);
//        } else {
//            itemMapper.updateItemStatus(oldStatus, ItemStatus.CANCEL_SUCCESS, itemId);
//        }
//    }

    /**
     * 标校验
     *
     * @param itemIds 标id数组
     * @return
     */
    public Boolean packageCheck(String[] itemIds) {
        //校验
        String verifyStr = "";
        for (int i = 0; i < itemIds.length; i++) {
            Integer id = Integer.parseInt(itemIds[i]);
            //查询项目信息
            BasItem item = itemMapper.selectByPrimaryKey(id);
            //判断是否是第一个项目，是：将校验参数存在verifyStr中。否则开始校验
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (i == 0) {
                //还款方式
                verifyStr += item.getItemRepayMethod();
                //期限和期限单位
                verifyStr += item.getItemCycle();
                verifyStr += item.getItemCycleUnit();
                //利率+加息利率
                verifyStr += item.getItemRate().add(item.getItemAddRate());
                //起息日
                if (item.getInterestTime() != null) {
                    verifyStr += sdf.format(item.getInterestTime());
                }

            } else {
                String actualStr = "";
                //还款方式
                actualStr += item.getItemRepayMethod();
                //期限和期限单位
                actualStr += item.getItemCycle();
                actualStr += item.getItemCycleUnit();
                //利率+加息利率
                actualStr += item.getItemRate().add(item.getItemAddRate());
                //起息日
                if (item.getInterestTime() != null) {
                    actualStr += sdf.format(item.getInterestTime());
                }
                //如果量字符串不相等，则表示标不属于用一类型。不能打包
                if (!actualStr.equals(verifyStr)) {
                    return false;
                }
            }
        }
        return true;
    }
}
